package com.thb.pay.manage.web.agent;

import com.google.common.collect.Lists;
import com.thb.pay.api.agent.AgentAccountServiceApi;
import com.thb.pay.api.agent.AgentInfoServiceApi;
import com.thb.pay.api.agent.vo.req.AgentInfoPageReq;
import com.thb.pay.api.agent.vo.req.AgentInfoReq;
import com.thb.pay.api.agent.vo.resp.AgentAccountVo;
import com.thb.pay.api.agent.vo.resp.AgentInfoVo;
import com.thb.pay.api.sys.SysConfigServiceApi;
import com.thb.pay.api.sys.vo.resp.SysConfigVo;
import com.thb.pay.core.annotation.OperationLog;
import com.thb.pay.core.enums.CommConfigEnum;
import com.thb.pay.core.exception.RRException;
import com.thb.pay.core.utils.Constant;
import com.thb.pay.core.utils.PageResult;
import com.thb.pay.core.utils.R;
import com.thb.pay.manage.comm.controller.BaseController;
import com.thb.pay.manage.enums.AgentExceptionEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/sys/agentInfo")
public class AgentInfoController extends BaseController {

    @Autowired
    private AgentInfoServiceApi agentInfoServiceApi;

    @Autowired
    private AgentAccountServiceApi agentAccountServiceApi;

    @Autowired
    private SysConfigServiceApi sysConfigServiceApi;

    @PostMapping("/list")
    public R list(@RequestBody AgentInfoPageReq pageReq) {

        PageResult<AgentInfoVo> pageResult = agentInfoServiceApi.findPage(pageReq);
        if (pageResult.getTotal() == 0) {
            return R.ok(pageResult);
        }
        SysConfigVo sysConfigVo = sysConfigServiceApi.getByCode(CommConfigEnum.AGENT_LOGIN_URL.code());
        List<Long> agentIds = Lists.newArrayList();
        pageResult.getRecords().forEach(agentInfoVo -> {
            agentIds.add(agentInfoVo.getId());
        });
        Map<Long, AgentAccountVo> agentAccountVoMap = agentAccountServiceApi.findByIds(agentIds);
        pageResult.getRecords().forEach(agentInfoVo -> {
            agentInfoVo.setLoginUrl(sysConfigVo != null ? sysConfigVo.getValue() : "");//设置登入地址
            AgentAccountVo agentAccountVo = agentAccountVoMap.get(agentInfoVo.getId());//设置账户余额
            agentInfoVo.setBalance(agentAccountVo != null ? BigDecimal.valueOf(agentAccountVo.getBalance()) : BigDecimal.ZERO);
        });
        return R.ok(pageResult);
    }

    @PostMapping("/get")
    @ResponseBody
    public R get(@RequestParam("agentId") Long agentId) {
        AgentInfoVo resultData = agentInfoServiceApi.getByAgentId(agentId);
        return R.ok(resultData);
    }

    /**
     * 查询一级、二级代理商ID
     *
     * @return
     */
    @PostMapping("/getParentAgentId")
    @ResponseBody
    public R getParentAgentId(@RequestBody AgentInfoReq agentInfoReq) {
        List<AgentInfoVo> resultData = agentInfoServiceApi.findListByAgent(agentInfoReq);
        return R.ok(resultData);
    }

    /**
     * 新增代理商信息
     *
     * @return
     */
    @PostMapping("/add")
    @OperationLog(value = "新增代理商")
    public R add(@RequestBody AgentInfoReq agentInfo) {
        // 设置默认登录密码
        agentInfo.setPassword(Constant.DEFAULT_PASSWORD);
        agentInfo.setLastPasswordResetTime(new Date());
        // 设置默认支付密码
        agentInfo.setPayPassword(Constant.DEFAULT_PASSWORD);
        // 验证一级代理ID
        if (agentInfo.getParentId() == null) {
            agentInfo.setParentId(0L);//设置为一级代理
        }
        //校验登入账号名是否存在
        AgentInfoVo checkAgentInfoExistByLoginUserName = agentInfoServiceApi.getByLoginName(agentInfo.getUserName());
        if (checkAgentInfoExistByLoginUserName != null) {
            throw RRException.build(AgentExceptionEnum.AGENT_EXIST);
        }
        if (agentInfo.getParentId() != 0) {
            AgentInfoVo parentAgentVo = agentInfoServiceApi.getByAgentId(agentInfo.getParentId());
            if (parentAgentVo == null) {
                throw RRException.build(AgentExceptionEnum.PARENT_AGENT_NOT_EXIST);
            }
            //非一级代理 校验最多可以设置几层代理,由系统参数进行控制
            SysConfigVo sysConfigVo = sysConfigServiceApi.getByCode(CommConfigEnum.AGENT_MAX_LEVEL.code());
            Integer maxAgentLevel = Integer.valueOf(CommConfigEnum.AGENT_MAX_LEVEL.defaultValue());
            if (sysConfigVo != null) {
                maxAgentLevel = Integer.valueOf(sysConfigVo.getValue());
            }
            if (parentAgentVo.getLevel() >= maxAgentLevel) {
                throw RRException.build(AgentExceptionEnum.EXCEED_AGENT_MAX_LEVEL);
            }
            agentInfo.setLevel(parentAgentVo.getLevel() + 1);
        } else {
            agentInfo.setLevel(1);
        }
        agentInfoServiceApi.add(agentInfo);
        return R.ok();
    }

    /**
     * 修改代理商信息
     *
     * @return
     */
    @PostMapping("/update")
    @OperationLog(value = "修改代理商")
    public R update(@RequestBody AgentInfoReq agentInfoReq) {
        AgentInfoVo targetAgentVo = agentInfoServiceApi.getByAgentId(agentInfoReq.getId());
        if (targetAgentVo == null) {
            throw RRException.build(AgentExceptionEnum.AGENT_NOT_EXIST);
        }
        if (agentInfoReq.getParentId() != null && agentInfoReq.getParentId() != 0) {
            AgentInfoVo parentAgentVo = agentInfoServiceApi.getByAgentId(agentInfoReq.getParentId());
            if (parentAgentVo == null) {
                throw RRException.build(AgentExceptionEnum.PARENT_AGENT_NOT_EXIST);
            }
        }
        String rawPassword = agentInfoReq.getPassword();
        if (StringUtils.isNotBlank(rawPassword)) {
            agentInfoReq.setPassword(rawPassword);
            agentInfoReq.setLastPasswordResetTime(new Date());
        }

        String payPassword = agentInfoReq.getPayPassword();
        if (StringUtils.isNotBlank(payPassword)) {
            //则修改支付密码
            agentInfoReq.setPayPassword(payPassword);
        }
        agentInfoServiceApi.update(agentInfoReq);
        return R.ok();
    }

    /**
     * 修改结算设置
     *
     * @return
     */
    @RequestMapping("/updateSettle")
    @OperationLog(value = "修改代理商结算信息")
    public R updateSettle(@RequestBody AgentInfoReq updateAgentInfo) {

        AgentInfoVo targetAgentVo = agentInfoServiceApi.getByAgentId(updateAgentInfo.getId());
        if (targetAgentVo == null) {
            throw RRException.build(AgentExceptionEnum.AGENT_NOT_EXIST);
        }

        agentInfoServiceApi.update(updateAgentInfo);
        return R.ok();
    }


    /**
     * 重置商户密码
     *
     * @return
     */
    @PostMapping("/resetPassword")
    @OperationLog(value = "重置代理商密码")
    public R resetPassword(@RequestBody AgentInfoReq agentInfoReq) {
        AgentInfoVo targetAgentVo = agentInfoServiceApi.getByAgentId(agentInfoReq.getId());
        if (targetAgentVo == null) {
            throw RRException.build(AgentExceptionEnum.AGENT_NOT_EXIST);
        }
        AgentInfoReq updateAgentInfo = new AgentInfoReq();
        updateAgentInfo.setId(agentInfoReq.getId());
        updateAgentInfo.setPassword(agentInfoReq.getPassword());
        updateAgentInfo.setLastPasswordResetTime(new Date());
        agentInfoServiceApi.update(updateAgentInfo);
        return R.ok();
    }

}